package com.tangyuan.live.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tangyuan.common.result.Result;
import com.tangyuan.common.result.ResultCodeEnum;
import com.tangyuan.live.mapper.LiveGroupMapper;
import com.tangyuan.live.service.LiveGroupService;
import com.tangyuan.live.util.IMUtil;
import com.tangyuan.model.live.LiveGroup;
import com.tangyuan.model.live.LiveRoom;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class LiveGroupServiceImpl extends ServiceImpl<LiveGroupMapper, LiveGroup> implements LiveGroupService  {

    @Autowired
    IMUtil imUtil;


    @Override
    public Result<String> createGroup(LiveRoom room) {
        String group = imUtil.createGroup(room);
        if(StrUtil.isEmpty(group)){
            return Result.build(null, ResultCodeEnum.CREATE_LIVE_ERROR);
        }
        String groupId = new JSONObject(group).get("GroupId").toString();
        LiveGroup liveGroup = new LiveGroup();
        liveGroup.setGroupId(groupId);
        liveGroup.setStatus(1);
        liveGroup.setCreateTime(new Date());
        baseMapper.insert(liveGroup);
        return Result.ok(groupId);
    }

    @Override
    public void destroyGroup(String groupId) {
        LiveGroup liveGroup = getByGroupId(groupId);
        if(liveGroup == null){
            log.error("群组不存在:{}",groupId);
            return;
        }
        if(liveGroup.getStatus() == 2){
            log.info("群组已解散:{}",groupId);
            return;
        }
        String group = imUtil.destroyGroup(groupId);
        if(StrUtil.isEmpty(group)){
            log.error("群组:{}解散失败",groupId);
            return;
        }
        liveGroup.setStatus(2);
        liveGroup.setEndTime(new Date());
        baseMapper.updateById(liveGroup);
    }

    @Override
    public Date getMaxNoCloseLiveTime() {
        return baseMapper.getMaxNoCloseLiveTime();
    }

    @Override
    public void setCutoffLive(List<String> groupId) {
        if(CollectionUtils.isEmpty(groupId)){
            return;
        }
        baseMapper.update(null,new LambdaUpdateWrapper<LiveGroup>()
                .set(LiveGroup::getDissolveWay,2)
                .in(LiveGroup::getGroupId,groupId));
    }

    public LiveGroup getByGroupId(String groupId){
        if(StrUtil.isEmpty(groupId)){
            return null;
        }
        LambdaQueryWrapper<LiveGroup> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LiveGroup::getGroupId,groupId);
        return baseMapper.selectOne(wrapper);
    }
}
